package tas.xml;

import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class TreeXml {

    public TreeXml() {
    }

    public String tree(List<Object[]> list) {
        String result = null;
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.newDocument();

            // inicio de tree
            Element root = doc.createElement("tree");
            root.setAttribute("id", "0");
            doc.appendChild(root);

            // el primer padre
            Object[] f = (Object[]) list.get(0);

            Element nodo = doc.createElement("item");
            nodo.setAttribute("text", f[3].toString());
            nodo.setAttribute("id", "1");
            root.appendChild(nodo);
            // ---

            treedoc(doc, nodo, list.subList(1, list.size()), 2);

            result = xmlToString(doc);

        } catch (ParserConfigurationException e) {
        }

        return result;
    }

    private void treedoc(Document doc, Element nodo, List<Object[]> list, int _id) {
        for (Object[] f : list) {
            String padre = f[1].toString();

            if (nodo.getAttribute("text").equals(padre)) {
                Element hijo = doc.createElement("item");
                hijo.setAttribute("text", f[3].toString());
                hijo.setAttribute("id", "" + _id);
                nodo.appendChild(hijo);
                
                treedoc(doc, hijo, list, _id);
            }
            
            ++_id;
        }
    }

    // XML es retornado como String.
    public String xmlToString(Document document) {

        String sxml = null;

        try {
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(document);

            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            transformer.transform(source, result);

            sxml = result.getWriter().toString();
            writer.close();

        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        } catch (TransformerException ex) {
            System.out.println(ex.getMessage());
        }

        return sxml;
    }
}
